package com.htjx.mall.admin.controllers;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.htjx.mall.admin.controllers.vo.ProductQuery;
import com.htjx.mall.commons.api.CommonConstant;
import com.htjx.mall.commons.api.Result;
import com.htjx.mall.commons.models.product.Brand;
import com.htjx.mall.commons.models.product.Catalog;
import com.htjx.mall.commons.models.product.Category;
import com.htjx.mall.commons.models.product.Introduce;
import com.htjx.mall.commons.models.product.IntroduceAPIs;
import com.htjx.mall.commons.models.product.Product;
import com.htjx.mall.commons.utils.Dates;
import com.htjx.mall.commons.utils.page.Page;
import com.htjx.mall.services.BrandService;
import com.htjx.mall.services.CatalogService;
import com.htjx.mall.services.CategoryService;
import com.htjx.mall.services.ProductService;
import com.htjx.mall.services.SpecificationService;

@Controller
@RequestMapping("/admin/product")
public class _ProductController {
	@Autowired
	private ProductService productService;
	@Autowired
	private CatalogService catalogService;
	@Autowired
	private BrandService brandService;
	@Autowired
	private SpecificationService specificationService;
	@Autowired
	private CategoryService categoryService;
	
	/****
	 * 分页查询商品
	 * @param productQuery
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String productList(ProductQuery productQuery, Model model) {
		Page<Product> page = new Page<Product>();
		page.setPageSize(productQuery.getPageSize());
		page.setPageNo(productQuery.getPageNo());
		page = productService.page(productQuery, page);
		
		List<Category> category = categoryService.selectByActive(true);
		List<Brand> brand = brandService.selectByActive(true);
		
		model.addAttribute("page", page);
		model.addAttribute("category", category);
		model.addAttribute("brand", brand);
		return "product/list";
	}
	
	@RequestMapping(value = "/detail/{product_id}", method = RequestMethod.GET)
	public String productDetail(@PathVariable("product_id") long id, Model model) {
		Product product = productService.findUniqueBy("id", String.valueOf(id));
		Result result = null;
		if(product == null) {
			result = new Result(9,"查询商品失败");
		} 
		
		// 查询该商品的品类
		List<Catalog> listCatalog = catalogService.SelectByProductId(id);
		 
		model.addAttribute("result", result);
		model.addAttribute("product", product);
		model.addAttribute("list_catalog", listCatalog);
		return "product/detail";
	}
	
	@RequestMapping(value = "/update/{product_id}", method = RequestMethod.GET)
	public String update(@PathVariable("product_id") long id, Model model) {
		Product product = productService.findUniqueBy("id", String.valueOf(id));
		Result result = null;
		if(product == null) {
			result = new Result(9,"查询商品失败");
		} 
		List<Category> category = categoryService.selectByActive(true);
		List<Brand> brand = brandService.selectByActive(true);

		model.addAttribute("result", result);
		model.addAttribute("product", product);
		model.addAttribute("category", category);
		model.addAttribute("brand", brand);
		return "product/update";
	}
	
	/****
	 * 更新一个商品
	 * @param productQuery
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(Product product, @RequestParam(value = "img_file", required=false) MultipartFile imgFile, Model model, HttpServletRequest request) {
		String name = product.getName();
		if(StringUtils.isBlank(name)) {
			model.addAttribute("result", new Result(9,"商品名称不能为空"));
			return "product/update";
		}
		
		long category_id = product.getCategory_id();
		if(category_id == 0) {
			model.addAttribute("result", new Result(9,"商品种类不能为空"));
			return "product/update";
		}
		
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		if(StringUtils.isNotBlank(originalFileName)) {
//			String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
//			String filePath = "/images/product/"+Dates.toYYYY_MM_DD(new Date());
//			String realPath = request.getSession().getServletContext().getRealPath(filePath); 
//		    //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
//				
//			String fileName = Dates.toTimeString(new Date()) + fileType;
//	        try {
//				FileUtils.copyInputStreamToFile(imgFile.getInputStream(), new File(realPath, fileName));
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} 
			
			if(!checkImage(imgFile)) {
				model.addAttribute("result", new Result(9,"请上传 800k 以内的有效图片"));
				return "product/update";
			}
			
	        product.setImage(saveImage(imgFile, request));
		} 
		
		String description = product.getDescription();
		if(StringUtils.isBlank(description)) {
			model.addAttribute("result", new Result(9,"商品描述不能为空"));
			return "product/update";
		}
		
		product.setUpdate_time(new Date());
		productService.updateOne(product);
		model.addAttribute("result", new Result(0,"更新成功"));
//		try {
//			FileUtils.forceDelete(FileUtils.getFile(request.getSession().getServletContext().getRealPath(oldImage)));
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return "redirect:/admin/product/detail/"+product.getId();
	}
	
	@RequestMapping(value = "/add", method=RequestMethod.GET)
	public String add(Model model) {
		List<Category> category = categoryService.selectByActive(true);
		model.addAttribute("category", category);
		List<Brand> brand = brandService.selectByActive(true);
		model.addAttribute("brand", brand);
		model.addAttribute("product", new Product());
		return "product/add";
	}
	
	/****
	 * 新增一个商品
	 * @param productQuery
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/add", method=RequestMethod.POST)
	public String add(Product product,@RequestParam("img_file") MultipartFile imgFile, Model model, HttpServletRequest request) {
		String name = product.getName();
		if(StringUtils.isBlank(name)) {
			model.addAttribute("result", new Result(9,"请填写商品名称"));
			return "product/add";
		}
		
		long category_id = product.getCategory_id();
		if(category_id == 0) {
			model.addAttribute("result", new Result(9,"请选择商品种类"));
			return "product/add";
		}
		
		if(productService.checkUniqueByProperty("name", name)) {
			model.addAttribute("result", new Result(9,"该商品已被添加"));
			return "product/add";
		}
		
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		if(StringUtils.isBlank(originalFileName)) {
			model.addAttribute("result", new Result(9,"请上传商品图片"));
			return "product/add";
		}
		
		if(!checkImage(imgFile)) {
			model.addAttribute("result", new Result(9,"请上传 800k 以内的有效图片"));
			return "product/add";
		}
		
//		String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
//		String filePath = "/images/product/"+Dates.toYYYY_MM_DD(new Date());
//		String realPath = request.getSession().getServletContext().getRealPath(filePath); 
//	    //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
//			
//		String fileName = Dates.toTimeString(new Date()) + fileType;
//        try {
//			FileUtils.copyInputStreamToFile(imgFile.getInputStream(), new File(realPath, fileName));
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} 
//      product.setImage(filePath+"/"+fileName);
		product.setImage(saveImage(imgFile, request));
		
		String description = product.getDescription();
		if(StringUtils.isBlank(description)) {
			model.addAttribute("result", new Result(9,"请填写商品描述"));
			return "product/add";
		}
		
		product.setCreate_time(new Date());
		product.setUpdate_time(new Date());
		productService.insertOne(product);
		model.addAttribute("result", new Result(0,"商品添加成功"));
		return "redirect:list";
	}
	
	/****
	 * 商品展示 陈述 介绍
	 */
	@RequestMapping(value = "/introduce/{product_id}", method=RequestMethod.GET)
	public String getIntroduce(@PathVariable("product_id") long id, Model model, HttpServletRequest request) {
		Introduce introduce = new Introduce();
		introduce.setId(id);
		
		List<Introduce> introduceList = IntroduceAPIs.parseXml(getXmlFileName(id, request));
		
		model.addAttribute("introduce", introduce);
		model.addAttribute("introduceList", introduceList);
		return "product/introduce";
	}
	
	@RequestMapping(value = "/introduce/text/append", method=RequestMethod.POST)
	public String appendText(Introduce introduce, Model model, HttpServletRequest request) {
		
		introduce.setPlain(true);
		IntroduceAPIs.saveXml(getXmlFileName(introduce.getId(), request), introduce, -1);
		return "redirect:/admin/product/introduce/"+introduce.getId();
	}
	
	@RequestMapping(value = "/introduce/text/insert", method=RequestMethod.POST)
	public String insertText(Introduce introduce, int index, Model model, HttpServletRequest request) {
		
		introduce.setPlain(true);
		IntroduceAPIs.saveXml(getXmlFileName(introduce.getId(), request), introduce, index);
		return "redirect:/admin/product/introduce/"+introduce.getId();
	}
	
	@RequestMapping(value = "/introduce/delete", method=RequestMethod.POST)
	public String deleteIntroduce(long id, int index, Model model, HttpServletRequest request) {
		IntroduceAPIs.xmlDeleteElement(getXmlFileName(id, request), index);
		return "redirect:/admin/product/introduce/"+id;
	}
	
	@RequestMapping(value="/introduce/image/append", method=RequestMethod.POST)  
    public String appendImage(@RequestParam("img_file") MultipartFile imgFile, Introduce introduce, HttpServletRequest request, Model model){  
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		if(StringUtils.isBlank(originalFileName)) {
			model.addAttribute("result", new Result(9,"请上传商品图片"));
			return "redirect:/admin/product/introduce/"+introduce.getId();
		}
		
		if(!checkImage(imgFile)) {
			model.addAttribute("result", new Result(9,"请上传 800k 以内的有效图片"));
			return "redirect:/admin/product/introduce/"+introduce.getId();
		}
		
		String image_src = saveImage(imgFile, request);
        introduce.setContent(image_src);
        introduce.setPlain(false);
        
		IntroduceAPIs.saveXml(getXmlFileName(introduce.getId(), request), introduce, -1);
        return "redirect:/admin/product/introduce/"+introduce.getId();
	}
	
	@RequestMapping(value="/introduce/image/insert", method=RequestMethod.POST)  
    public String insertImage(@RequestParam("img_file") MultipartFile imgFile, Introduce introduce, long id, int index, HttpServletRequest request, Model model){  
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		if(StringUtils.isBlank(originalFileName)) {
			model.addAttribute("result", new Result(9,"请上传商品图片"));
			return "redirect:/admin/product/introduce/"+introduce.getId();
		}
		
		if(!checkImage(imgFile)) {
			model.addAttribute("result", new Result(9,"请上传 800k 以内的有效图片"));
			return "redirect:/admin/product/introduce/"+introduce.getId();
		}
		
        String image_src = saveImage(imgFile, request);
        introduce.setContent(image_src);
        introduce.setPlain(false);
        
		IntroduceAPIs.saveXml(getXmlFileName(introduce.getId(), request), introduce, index);
        return "redirect:/admin/product/introduce/"+introduce.getId();
	}
	
	private String getXmlFileName(long id, HttpServletRequest request) {
		Product product = productService.findUniqueBy("id", String.valueOf(id));
		if(product == null) {
			return null;
		}
		String filePath = product.getIntroduce();
		if(StringUtils.isBlank(filePath)) {
			filePath = CommonConstant.SHARE_PATH+Dates.toYYYY_MM_DD(new Date())+"/xml";
			product.setIntroduce(filePath);
			productService.updateOne(product);
		}
		String realPath = request.getSession().getServletContext().getRealPath(filePath); 
	    File file = new File(realPath);    
	    //如果文件夹不存在则创建    
	    if (!file.exists() && !file.isDirectory())      
	    {
	    	try {
				FileUtils.forceMkdir(file);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
		String fileName = realPath+"/"+id+".xml";
		return fileName;
	}
	
	private boolean checkImage(MultipartFile imgFile) {
//		long size = imgFile.getSize();
//		if(size == 0 || size > 800000){
//			return false;
//		}
		
		return true;
	}
	
	private String saveImage(MultipartFile imgFile, HttpServletRequest request) {
		// 处理图片
		String originalFileName = imgFile.getOriginalFilename();
		String fileType = imgFile.getOriginalFilename().substring(originalFileName.lastIndexOf("."));
		String filePath = CommonConstant.SHARE_PATH+Dates.toYYYY_MM_DD(new Date())+"/images";
		String realPath = request.getSession().getServletContext().getRealPath(filePath); 
	    //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
			
		String fileName = Dates.toTimeString(new Date()) + fileType;
        try {
			FileUtils.copyInputStreamToFile(imgFile.getInputStream(), new File(realPath, fileName));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        
        String image_src = filePath+"/"+fileName;
        return image_src;
	}
	
}
